package nl.saxion.dbi.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.hsqldb.server.Server;

public class DatabaseManager {

	private static Server hsqlServer = null;
	private static Connection connection = null;

	private static DatabaseManager instance = null;

	public static DatabaseManager getInstance() {
		if (instance == null) {
			instance = new DatabaseManager();
		}
		return instance;
	}

	public DatabaseManager() {
		try {
			setupServer();
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		}
	}

	private static void setupServer() throws ClassNotFoundException,
			SQLException {
		hsqlServer = new Server();
		hsqlServer.setLogWriter(null);
		hsqlServer.setSilent(true);
		hsqlServer.setDatabaseName(0, "BazenbaseServer");
		hsqlServer.setDatabasePath(0, "file:BazenbaseServer");
		hsqlServer.start();

		Class.forName("org.hsqldb.jdbcDriver");

		connection = DriverManager.getConnection(
				"jdbc:hsqldb:hsql://localhost/BazenbaseServer", "SA", "");
		connection.setAutoCommit(true);
	}

	public Connection getConnection() {
		return connection;
	}

	public static void stopServer() {
		hsqlServer.stop();
		System.out.println("Stopped Bazenbase Server! Jippie :-D");
	}

}
